#!/usr/bin/python
# coding=utf-8

import urllib
import urlparse
import re
import datetime
from helpers import read_url, decode

patterns = {
    'shortname': re.compile('-\s*([^<]+)</TITLE>', re.I|re.M),
    'mail': re.compile('<a href="mailto:([^"]+)">', re.I|re.M),
    'www': re.compile('<a href="(http://[^"]+)">http://[^<]+</a>', re.I|re.M),
    'members_url':  re.compile('<a href="(.*?pos_[^"]+)">[0-9]+ pos', re.I|re.M),
    'secretary_phones': re.compile('<td class="a4">(?:<strong>)?Sekretariat klubu(?:</strong>)?</td>.*?<tr>.*?</td>.*?</td>\s*<td>([^<]+)</td>', re.S|re.I|re.M),
}

def get_shortname(soup):
    try:
        match = patterns['shortname'].search(soup)
        return match.group(1)
    except:
        return None

def get_mail(soup):
    match = patterns['mail'].search(soup)
    return match.group(1)

def get_www(soup):
    match = patterns['www'].search(soup)
    if not match:
        return None
    return match.group(1)

def get_secretary_phones(soup):
    match = patterns['secretary_phones'].search(soup)
    return match.group(1)

def get_members_url(soup):
    match = patterns['members_url'].search(soup)
    if not match:
        print soup
    return match.group(1)

def get_party(path):
    source = read_url(path)
    party = {
        'shortname': decode(get_shortname(source)),
        'email': get_mail(source),
        'www': get_www(source),
        'path': path,
        'members_url': urlparse.urljoin(path, get_members_url(source)),
        'secretary_phones': get_secretary_phones(source),
    }
    return party


def main():
    path = 'http://sejm.gov.pl/poslowie/kluby/kont_po.htm'
    party = get_party(path)
    print party
    

if __name__ == "__main__":
    main()
